﻿using FrameServer.Net;
using System;
using System.Collections.Generic;

namespace FrameServer.Handler
{
    class RoomHandler
    {
        private Dictionary<string, PlayerState> _stateMap = new Dictionary<string, PlayerState>();
        private System.Timers.Timer _timer;

        public RoomHandler()
        {
            NetMsgHandler.Instance.RegisterReq(NetMsgID.CsEnterRoom, HandleEnterRoom);
            NetMsgHandler.Instance.RegisterReq(NetMsgID.CsSyncState, HandleSyncState);

            _timer = new System.Timers.Timer(200);
            _timer.Elapsed += OnTimedEvent;
            _timer.AutoReset = true;
            _timer.Enabled = true;
        }

        private void HandleEnterRoom(byte[] buff, TCPClientPeer clientPeer)
        {

        }

        private void HandleSyncState(byte[] buff, TCPClientPeer clientPeer)
        {
            CS_SyncState data = NetPacket.Deserialize<CS_SyncState>(buff);
            var state = new PlayerState
            {
                Token = clientPeer.token,
                Pos = data.Pos,
                Scale = data.Scale,
                Anim = data.Anim,
                Count = data.Count,
            };
            _stateMap[clientPeer.token] = state;
        }

        private void NtfState()
        {
            var resp = new SC_NtfStates();
            resp.States.AddRange(_stateMap.Values);
            foreach (var clientPeer in TCPServer.Instance.clientPeerMap.Values)
            {
                clientPeer.SendTcpMsg(NetMsgID.ScNtfStates, resp);
            }
            _stateMap.Clear();
        }

        private void OnTimedEvent(object sender, System.Timers.ElapsedEventArgs e)
        {
            NtfState();
        }
    }
}
